<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//按收入分担
class ShareIncome extends CommonController {

	function __construct(){
		
		parent::__construct();
		
		$this->load->model('Accounting/accountingModel','CurModel');
	}
	
	
	//start
	/**
	* @name 获取数据
	* @param xdata ture char 横向
	* @param ydata ture char 纵向
	* @param f ture char 筛选
	* @return 成功返回1
	*/
	//end
	function get_data(){
		
		if(!$this->check_priv('accounting_income|accounting_income_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$xdata = $this->input->post('xdata',null,array());
		$ydata = $this->input->post('ydata',null,array());
		$filter = $this->input->post('f',null,array());
		
		if(empty($filter['date_month'])){
			$this->err_out('请选择月份');
		}

		
		$xlist = $this->get_xlist($xdata,$ydata);
		
		if(!isset($ydata['list'])){
			$this->err_out('请选择纵向数据');
		}
		$ylist = array();
		$ls_list = $ydata['list'];
		
		/*if($ydata['info']['bz'] != '人民币'){
			$this->load->model('User/CurrencyModel','CurrencyModel');
			$curr = $this->CurrencyModel->bz_get_info($ydata['info']['bz']);
			$bs = $curr?$curr['exchange_rate']:1;
		}else{
			$bs = 1;
		}*/

		//$bs = !empty($ydata['info']['exchange_rate'])?$ydata['info']['exchange_rate']:1;
		$ex_arr = array('6041装修','6042汽车','6043傢俬設備');
		$total = 0;//$this->data_out($xlist);exit;
		foreach($ls_list as $key=>$val){
			$ls_data = array();
			$ls_data['name'] = $val;
			
			$arr = array(
				'date_month'=>$filter['date_month'],
				'bumen' => $filter['bumen'],
				'subject'=>$val
			);

			if(in_array($val,$ex_arr)){
				$ress = $this->get_gd_totals($arr);
				//$ls_total = $this->CurModel->get_totals($arr);
			}else{
				$ress = $this->CurModel->get_money_totals($arr);//$this->data_out($ress);exit;
			}
			$ls_total = $ress['num'];
			
			$ls_data['total'] = $ls_total;
			$ls_data['bz'] = $ress['bz'];
			$total += $ls_data['total'];
			/*
			foreach($xlist as $k=>$v){
				if($k<2){
					continue;
				}
				if(!isset($v['children'])){
					$arr = array(
						'date_month'=>$filter['date_month'],
						'subject'=>$val,
						'bumen'=>$v['value']
					);
					//$ls_total =  $this->CurModel->get_totals($arr);
					//$ls_data[$v['key']] = $ls_total * $bs;
				}
				else{
					foreach($v['children'] as $item){
						$arr = array(
							'date_month'=>$filter['date_month'],
							'subject'=>$val,
							'bumen'=>$v['value'],
							'region'=>$item['value']
						);
						//$ls_total =  $this->CurModel->get_totals($arr);
						//$ls_data[$item['key']] = $ls_total * $bs;
					}
				}
				
			}
			*/
			
			$ylist[] = $ls_data;
		}
		
		$ls_data = array(
			'name'=>'分摊费用',
			'bz' => $ress['bz'],
			'total'=>$total
		);
		
		//如果自定义金额存在
		if(isset($ydata['info']['exchange_rate']) && $ydata['info']['exchange_rate']){
			$ls_data['total'] = $total + $ydata['info']['exchange_rate'];
			$ls_data['cus_total'] = $ydata['info']['exchange_rate'];
		}

		$ylist[] = $ls_data;
		
		$data = array(
			'xlist'=>$xlist,
			'ylist'=>$ylist
		);
		
		
		$this->data_out($data);
	}

	function new_get_data(){
		
		if(!$this->check_priv('accounting_member|accounting_member_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$xdata = $this->input->post('xdata',null,array());
		$ydata = $this->input->post('ydata',null,array());
		$filter = $this->input->post('f',null,array());
		
		if(empty($filter['date_month'])){
			$this->err_out('请选择月份');
		}
		
		
		$xlist = $this->get_xlist($xdata,$ydata);
		
		if(!isset($ydata['list']) && !$filter['bumen']){
			$this->err_out('请选择纵向数据');
		}

		$ylist = array();
		if(isset($ydata['list'])){
			$ls_list = $ydata['list'];
		}else{//否则就只有部门，没选择科目的情况下
			
			$re22 = $this->CurModel->get_subject_by_bumen($filter);
			
			if(!$re22){
				$ls_data = array();

				$ls_data = array(
					'name'=>'分摊费用',
					'bz' => '',
					'total'=>0
				);
				//如果自定义金额存在
				if(isset($ydata['info']['exchange_rate']) && $ydata['info']['exchange_rate']){
					$ls_data['total'] = $ydata['info']['exchange_rate'];
					$ls_data['cus_total'] = $ydata['info']['exchange_rate'];
				}

				$ylist[] = $ls_data;
		
				$data = array(
					'xlist'=>$xlist,
					'ylist'=>$ylist
				);
				
			}else{
				foreach ($re22 as $v) {
					$ls_list[] = $v['subject'];
				}
			}
		}
		
		$ex_arr = array('6041装修','6042汽车','6043傢俬設備');
		$total = 0;
		foreach($ls_list as $key=>$val){
			$ls_data = array();
			$ls_data['name'] = $val;
			
			$arr = array(
				'date_month'=>$filter['date_month'],
				'bumen' => $filter['bumen'],
				'subject'=>$val
			);

			if(in_array($val,$ex_arr)){
				$ress = $this->get_gd_totals($arr);
			}else{
				$ress = $this->CurModel->get_money_totals($arr);//$this->data_out($ress);exit;
			}
			$ls_total = $ress['num'];
			
			$ls_data['total'] = $ls_total;
			$ls_data['bz'] = $ress['bz'];
			$total += $ls_data['total'];
			
			$ylist[] = $ls_data;
		}

		$ls_data = array(
			'name'=>'分摊费用',
			'bz' => $ress['bz'],
			'total'=>$total
		);

		//如果自定义金额存在
		if(isset($ydata['info']['exchange_rate']) && $ydata['info']['exchange_rate']){
			$ls_data['total'] = $total + $ydata['info']['exchange_rate'];
			$ls_data['cus_total'] = $ydata['info']['exchange_rate'];
		}

		$ylist[] = $ls_data;
		
		$data = array(
			'xlist'=>$xlist,
			'ylist'=>$ylist
		);
		
		
		$this->data_out($data);
	}

	function get_gd_totals($data){
		
		//获取相关的数据
		$where = array(
			'useless_date' => date("Ym",strtotime($data['date_month'])),
			'subject' => $data['subject'],
			'bumen' => $data['bumen']
		);
		$this->load->model('Accounting/AssetsModel','assetsModel');
		$gd_list = $this->assetsModel->get_all($where);
		if(count($gd_list) > 0){
			$money = 0;
			$current_date = $data['date_month'];
			foreach($gd_list as $val){

				if($val['status']==1){//报废
					$month_num = $this->getMonthNum($val['start_date'],$current_date);
					$balance = $val['money'] - ($month_num * $val['depreciation']);//正常累计折旧期末余额
					$money += $val['depreciation'] + $balance;
				}else{//在用
					$money += $val['depreciation'];
				}

			}
			return array('num'=>$money,'bz'=>$gd_list[0]['bz']);
		}else{
			return array('num'=>0,'bz'=>'');
		}
	}
	
	function get_xlist($xdata,$ydata){
		$xlist = array();
		$name = '表头';
		// $name = !empty($ydata['info']['name'])?$ydata['info']['name']:'表头';
		// if(!empty($ydata['info']['bz'])){
		// 	$name .="({$ydata['info']['bz']})";
		// }
		
		
		$xlist[] = array('key'=>'name','value'=>$name);
		$xlist[] = array('key'=>'bz','value'=>'币种');
		$xlist[] = array('key'=>'total','value'=>'总金额');
			
		foreach($xdata as $key=>$val){
			if(empty($val['name'])){
				continue;
			}
			$ls_data = array();
			$ls_data['key'] = 'bumen'.$key;
			$ls_data['value'] = $val['name'];
			$ls_data['classRule'] = $val['classRule'];
			
			
			if(isset($val['data'])){
				$ls_children = array();
				
				foreach($val['data'] as $k=>$v){
					$ls_children[] = array(
						//'key'=>'children'.$k,
						'key'=>'bumen'.$key.'_'.$k,
						'value'=>$v
					);
				}
				$ls_data['children'] = $ls_children;
			}

			$xlist[] = $ls_data;
		}
		return $xlist;
	}

	
	//导出人员分摊
	function export_data(){
		
		if(!$this->check_priv('accounting_income|accounting_income_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		
		$xdata = $this->input->post('xdata',null,array());
		$ydata = $this->input->post('ydata',null,array());
		$filter = $this->input->post('f',null,array());
		$exps = $this->input->post('exps',null,array());
		
		if(empty($filter['date_month'])){
			$this->err_out('请选择月份');
		}
		
		
		
		$xlist = array();
		
		$name = !empty($ydata['info']['name'])?$ydata['info']['name']:'表头';
		if(!empty($ydata['info']['bz'])){
			$name .="({$ydata['info']['bz']})";
		}

		
		$index = 0;
		foreach($exps as $val){
			$index++;
		}
		if($index<=0){
			//$this->err_out('请先搜索出数据，然后设置指数后再操作导出');
		}
		
		$xlist = $this->get_xlist($xdata,$ydata);
		
		$merges = array();
		$arr = array();
		
		$ls_index = 0;
		foreach($xlist as $key=>$val){
			$col = $this->get_char($key,'A');
			
			$arr[$col.'2'] = $val['value'];
			if(isset($val['children'])){
				
				foreach($val['children'] as $k=>$v){
					$ls_col = $this->get_char($k,$col);
					$arr[$ls_col.'3'] = $v['value'];
					
					$ls_exp = isset($exps[$v['key']])?$exps[$v['key']]:0;
					$arr[$ls_col.'4'] = $ls_exp;
					$ls_index++;
				}
				
				
				$start = $col.'2';
				$ls_col = $this->get_char(count($val['children'])-1,$col);
				$end = $ls_col.'2';
				$merges[] = $start.':'.$end;
			}
			else{
				$ls_exp = isset($exps[$val['key']])?$exps[$val['key']]:0;
				$arr[$col.'4'] = $ls_exp;
				$ls_index++;
			}
		}
		
		$arr['A1'] = date('Y年m月',strtotime($filter['date_month'].'-01'));
		$ls_col = $this->get_char($ls_index-1,'A');;
		$merges[] = "A1:{$ls_col}1";
		
		/*
		$exp_total = 0;
		foreach($exps as $val){
			$exp_total += $val;
		}
		*/
		
		$line = 4;
		$arr['A'.$line] = '人员统计';
		$ls_col = $this->get_char($ls_index-1,'A');;
		$arr['B'.$line] = "=SUM(C{$line}:{$ls_col}{$line})";
		
		if(!isset($ydata['list'])){
			$this->err_out('请选择纵向数据');
		}
		
		$ylist = array();
		$ls_list = $ydata['list'];
		
		$bs = !empty($ydata['info']['exchange_rate'])?$ydata['info']['exchange_rate']:1;
		$total = 0;
		$line = 5;
		
		foreach($ls_list as $key=>$val){
			
			$arr['A'.$line] = $val;
			
			$ls_arr = array(
				'date_month'=>$filter['date_month'],
				'subject'=>$val
			);
			$ls_val = $this->CurModel->get_totals($ls_arr);
			$ls_total = $ls_val * $bs;
			$arr['B'.$line] = $ls_total;
			
			
			foreach($xlist as $k=>$v){
				if($k<2){
					continue;
				}
				
				if(!isset($v['children'])){
					$ls_col = $this->get_char($k,'A');
					
					//$exp = isset($exps[$v['key']])?$exps[$v['key']]:0;
					//$arr[$ls_col.$line] =  toFloat($ls_total / $exp_total  * $exp);
					
					$arr[$ls_col.$line] = "=B{$line}/B4*{$ls_col}4";
				}
				else{
					
					foreach($v['children'] as $index=>$item){
						$ls_col = $this->get_char($k+$index,'A');
						
						//$exp = isset($exps[$item['key']])?$exps[$item['key']]:0;
						//$arr[$ls_col.$line] =  toFloat($ls_total / $exp_total  * $exp);
						
						$arr[$ls_col.$line] = "=B{$line}/B4*{$ls_col}4";
					}
				}
			}
			
			
			$total += $ls_total;
			$line++;
		}
		
		$arr['A'.$line] = '分摊费用';
		$arr['B'.$line] = $total;
		
		foreach($xlist as $k=>$v){
			if($k<2){
				continue;
			}
			
			if(!isset($v['children'])){
				$ls_col = $this->get_char($k,'A');
				
				//$exp = isset($exps[$v['key']])?$exps[$v['key']]:0;
				//$arr[$ls_col.$line] =  toFloat($total / $exp_total  * $exp);
				
				$arr[$ls_col.$line] = "=B{$line}/B4*{$ls_col}4";
			}
			else{
				
				foreach($v['children'] as $index=>$item){
					$ls_col = $this->get_char($k+$index,'A');
					
					//$exp = isset($exps[$item['key']])?$exps[$item['key']]:0;
					//$arr[$ls_col.$line] =  toFloat($total / $exp_total  * $exp);
					$arr[$ls_col.$line] = "=B{$line}/B4*{$ls_col}4";
				}
			}
		}
		
		
		
		$result = $this->Excel_write($arr,$merges);
		if(!$result){
			$this->err_out('生成Excel文件失败');
		}
		
		$url = base_url($result);
		
		$this->data_out($url);
	}
	
	//新导出人员分摊
	function new_export_data(){
		
		if(!$this->check_priv('accounting_member|accounting_member_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$xdata = $this->input->post('xdata',null,array());
		$ydata = $this->input->post('ydata',null,array());
		$filter = $this->input->post('f',null,array());
		$exps = $this->input->post('exps',null,array());
		$cusexps = $this->input->post('cusexps',null,array());
		$list = $this->input->post('list',null,array());

		$new_ex = array();
		$fruit = $exps;
		reset($fruit);
		while (list($key, $val) = each($fruit)) {
		    $new_ex[] = array('key'=>$key,'val'=>$val);
		}
		
		if(empty($filter['date_month'])){
			$this->err_out('请选择月份');
		}
		
		if(!isset($ydata['list'])){
			$this->err_out('请选择纵向数据');
		}
		
		$xlist = array();
		
		$name = !empty($ydata['info']['name'])?$ydata['info']['name']:'表头';
		if(!empty($ydata['info']['bz'])){
			$name .="({$ydata['info']['bz']})";
		}

		
		$index = 0;
		foreach($exps as $val){
			$index++;
		}
		if($index<=0){
			//$this->err_out('请先搜索出数据，然后设置指数后再操作导出');
		}
		
		$xlist = $this->get_xlist($xdata,$ydata);
		
		$merges = array();
		$arr = array();

		$ls_index = 0;
		$had_col = '';//当有N个多分类的情况，防止被覆盖
		foreach($xlist as $key=>$val){
			$col = $this->get_char($key,'A');
			
			//$arr[$col.'2'] = $val['value'];
			if(isset($val['children'])){
				
				foreach($val['children'] as $k=>$v){
					$col = $had_col?$this->get_char(1,$had_col):$col;
					$ls_col = $this->get_char($k,$col);
					$arr[$ls_col.'2'] = $val['value'];
					$arr[$ls_col.'3'] = $v['value'];
					
					$ls_exp = isset($exps[$v['key']])?$exps[$v['key']]:0;
					$arr[$ls_col.'4'] = $ls_exp;
					$cus_exp = isset($cusexps[$v['key']])?$cusexps[$v['key']]:0;
					$arr[$ls_col.'5'] = $cus_exp;
					$ls_index++;
				}
				
				
				$start = $col.'2';
				$ls_col = $this->get_char(count($val['children'])-1,$col);
				$end = $ls_col.'2';
				$merges[] = $start.':'.$end;
				$had_col = $ls_col;
			}
			else{
				$col = $had_col?$this->get_char(1,$had_col):$col;
				$arr[$col.'2'] = $val['value'];
				$ls_exp = isset($exps[$val['key']])?$exps[$val['key']]:0;
				$arr[$col.'4'] = $ls_exp;
				$cus_exp = isset($cusexps[$val['key']])?$cusexps[$val['key']]:0;
				$arr[$col.'5'] = $cus_exp;
				$ls_index++;
			}
		}
		
		$arr['A1'] = date('Y年m月',strtotime($filter['date_month'].'-01'));
		$ls_col = $this->get_char($ls_index-1,'A');;
		$merges[] = "A1:{$ls_col}1";
		
		/*if($ydata['info']['bz'] != '人民币'){
			$this->load->model('User/CurrencyModel','CurrencyModel');
			$curr = $this->CurrencyModel->bz_get_info($ydata['info']['bz']);
			$bs = $curr?$curr['exchange_rate']:1;
		}else{
			$bs = 1;
		}*/
		
		$arr['A4'] = '人员统计';
		$arr['B4'] = '';
		$arr['C4'] = $list[0]['total'];
		$arr['A5'] = $ydata['info']['name'];
		$arr['B5'] = '';
		$arr['C5'] = $ydata['info']['exchange_rate'];
		$line = 6;
		foreach($list as $key=>$val){
			if($key<2){
				continue;
			}

			foreach($new_ex as $k=>$v){
				$col = $this->get_char($k,'D');
				$arr[$col.$line] = $val[$v['key']];
			}

			$arr['A'.$line] = $val['name'];
			$arr['B'.$line] = $val['bz'];
			$arr['C'.$line] = $val['total'];

			$line++;
		}
		//$this->data_out($arr);exit;
		$result = $this->Excel_write($arr,$merges);
		if(!$result){
			$this->err_out('生成Excel文件失败');
		}
		
		$url = base_url($result);
		
		$this->data_out($url);
	}
	
	function get_char($num,$pos='A'){
		if($num==0){
			return $pos;
		}

		for($i=0;$i<$num;$i++){
			$pos++;
		}
		return $pos;
	}
	
	function Excel_write($data,$merges=array()){
		$this->load->library('PHPExcel');
		
		// 创建Excel文件对象
		$objPHPExcel = new PHPExcel();
		// 设置文档信息，这个文档信息windows系统可以右键文件属性查看
		$objPHPExcel->getProperties()->setCreator("作者lalala")
			->setLastModifiedBy("最后更改者")
			->setTitle("文档标题")
			->setSubject("文档主题")
			->setDescription("文档的描述信息")
			->setKeywords("设置文档关键词")
			->setCategory("设置文档的分类");
		
		$objPHPExcel->setActiveSheetIndex(0);

		
									
		
		$objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		foreach($data as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($key,$val);
		}
		
		foreach($merges as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->mergeCells($val);
		}
		
		$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel ->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(0))->setAutoSize(true); 
		//$objPHPExcel->getActiveSheet()->setTitle('第一个sheet');

		// 设置第一个sheet为工作的sheet
		

		// 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$time = time();
		$dir  =  'upload/res/upload/other/'.date('Ymd');
		if(!is_dir(FCPATH . $dir)){
			@mkdir(FCPATH . $dir);
		}
		
		$file_name = $time.'_'.rand(10000,99999).'.xlsx';
		$objWriter->save(FCPATH . $dir .'/' .$file_name);
		
		return $dir .'/' .$file_name;
	}
	
	function getMonthNum($date1,$date2){
		$date1_stamp=strtotime($date1);
		$date2_stamp=strtotime($date2);

		if(date('Y-m',$date1_stamp) == date('Y-m',$date2_stamp)){
			return 1;
		}
		if($date1_stamp > $date2_stamp && date('Y-m',$date1_stamp) != date('Y-m',$date2_stamp)){
			return 0;
		}

		list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
		list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
		return abs(($date_2['y']-$date_1['y'])*12 +$date_2['m']-$date_1['m'])+1;
	}
	
}
